/**
 * 项目配置页面逻辑
 */

// 全局状态
let project = null;
let isLoading = false;

// DOM 元素
let elements = {};

/**
 * 初始化配置页面
 */
async function initConfigPage() {
  console.log('[Config] 初始化配置页面');
  
  // 等待API客户端初始化
  const apiReady = await waitForApi();
  if (!apiReady) {
    console.error('[Config] API客户端初始化失败');
    showToast('系统错误：无法初始化API客户端', 'error');
    setTimeout(() => goBack(), 3000);
    return;
  }
  
  console.log('[Config] API客户端已准备就绪');
  
  // 获取项目ID
  const projectId = getUrlParameter('project');
  if (!projectId) {
    showToast('缺少项目ID参数', 'error');
    setTimeout(() => goBack(), 2000);
    return;
  }
  
  // 获取DOM元素
  initElements();
  
  // 绑定事件
  bindEvents();
  
  // 加载项目数据
  await loadProject(projectId);
  

  
  console.log('[Config] 配置页面初始化完成');
}

/**
 * 初始化DOM元素
 */
function initElements() {
  elements = {
    // 容器
    loadingContainer: document.getElementById('loadingContainer'),
    configContainer: document.getElementById('configContainer'),
    
    // 头部信息
    projectSubtitle: document.getElementById('projectSubtitle'),
    projectStatus: document.getElementById('projectStatus'),
    statusText: document.getElementById('statusText'),
    statusDot: document.getElementById('statusDot'),
    
    // 基本信息
    projectNameEdit: document.getElementById('projectNameEdit'),
    renameBtn: document.getElementById('renameBtn'),
    createdAt: document.getElementById('createdAt'),
    updatedAt: document.getElementById('updatedAt'),
    projectId: document.getElementById('projectId'),
    
    // 环境配置
    testEnvironmentConfig: document.getElementById('testEnvironmentConfig'),
    productionEnvironmentConfig: document.getElementById('productionEnvironmentConfig'),
    testEnvStatus: document.getElementById('testEnvStatus'),
    prodEnvStatus: document.getElementById('prodEnvStatus'),
    
    // 自定义规则
    customRulesContainer: document.getElementById('customRulesContainer'),
    emptyCustomRules: document.getElementById('emptyCustomRules'),
    
    // 自定义规则表单
    customRuleLabel: document.getElementById('customRuleLabel'),
    customRuleValue: document.getElementById('customRuleValue'),
    confirmAddCustomRule: document.getElementById('confirmAddCustomRule'),
    

    
    // 操作按钮
    deleteProjectBtn: document.getElementById('deleteProjectBtn'),
    resetProjectBtn: document.getElementById('resetProjectBtn'),
    
    // 模态框
    deleteConfirmMessage: document.getElementById('deleteConfirmMessage'),
    confirmDeleteAction: document.getElementById('confirmDeleteAction'),
    
    // 新增元素
    testEnvSaveBtn: document.getElementById('testEnvSaveBtn'),
    prodEnvSaveBtn: document.getElementById('prodEnvSaveBtn'),
    addEnvironmentBtn: document.getElementById('addEnvironmentBtn'),
  };
}

/**
 * 绑定事件
 */
function bindEvents() {
  // 重命名（现在是保存）
  elements.renameBtn.addEventListener('click', handleRename);
  
  // 环境保存按钮
  elements.testEnvSaveBtn.addEventListener('click', saveTestEnvironment);
  elements.prodEnvSaveBtn.addEventListener('click', saveProductionEnvironment);
  
  // 新增环境按钮
  elements.addEnvironmentBtn.addEventListener('click', handleAddEnvironment);
  
      // 自定义规则（现在用于新增环境）
    elements.confirmAddCustomRule.addEventListener('click', handleAddCustomRule);
  
  // 危险操作
  elements.deleteProjectBtn.addEventListener('click', handleDeleteProject);
  elements.resetProjectBtn.addEventListener('click', handleResetProject);
  
  // 表单提交
  document.getElementById('addCustomRuleForm').addEventListener('submit', (e) => {
    e.preventDefault();
    handleAddCustomRule();
  });
  
  // 键盘快捷键
  document.addEventListener('keydown', handleKeyboard);
}

/**
 * 加载项目数据
 */
async function loadProject(projectId) {
  if (isLoading) return;
  
  // 检查API客户端
  if (!checkApiReady()) {
    return;
  }
  
  isLoading = true;
  showLoading();
  
  try {
    console.log(`[Config] 加载项目: ${projectId}`);
    const response = await api.getProject(projectId);
    
    if (response.success) {
      project = response.data;
      renderProject();
      showConfig();
    } else {
      throw new Error(response.error || '项目不存在');
    }
  } catch (error) {
    console.error('[Config] 加载项目失败:', error);
    showToast('加载项目失败: ' + error.message, 'error');
    setTimeout(() => goBack(), 3000);
  } finally {
    isLoading = false;
  }
}

/**
 * 渲染项目信息
 */
function renderProject() {
  if (!project) return;
  
  console.log(`[Config] 渲染项目: ${project.name}`);
  
  // 更新头部信息（如果元素存在）
  if (elements.projectSubtitle) {
    elements.projectSubtitle.textContent = project.name;
  }
  
  // 基本信息
  elements.projectNameEdit.value = project.name;
  
      // 环境配置
    elements.testEnvironmentConfig.value = project.environments.test || '';
    elements.productionEnvironmentConfig.value = project.environments.production || '';
    
    // 更新环境状态（如果元素存在）
    updateEnvironmentStatus();
    
    // 渲染自定义环境
    renderCustomEnvironments();
    
    // 自定义规则（如果容器存在）
    if (elements.customRulesContainer) {
      renderCustomRules();
    }
  

}

/**
 * 更新项目状态显示
 */
function updateProjectStatus() {
  if (!project) return;
  
  const { activeEnvironment } = project;
  let statusText = '未激活';
  let statusClass = 'inactive';
  
  if (activeEnvironment) {
    statusClass = 'active';
    
    if (activeEnvironment === 'test') {
      statusText = '测试环境';
    } else if (activeEnvironment === 'production') {
      statusText = '生产环境';
    } else if (activeEnvironment.startsWith('custom:')) {
      const ruleId = activeEnvironment.substring(7);
      const rule = project.customRules.find(r => r.id === ruleId);
      statusText = rule ? `自定义: ${rule.label}` : '自定义规则';
    }
  }
  
  // 检查元素是否存在再设置
  if (elements.statusText) {
    elements.statusText.textContent = statusText;
  }
  if (elements.statusDot) {
    elements.statusDot.className = `status-dot ${statusClass}`;
  }
}

/**
 * 更新环境状态
 */
function updateEnvironmentStatus() {
  if (!project) return;
  
  // 测试环境
  const testConfig = project.environments.test;
  const testConfigured = testConfig && testConfig.trim();
  const testActive = project.activeEnvironment === 'test';
  
  if (elements.testEnvStatus) {
    elements.testEnvStatus.textContent = testActive ? '已激活' : (testConfigured ? '已配置' : '未配置');
    elements.testEnvStatus.className = `environment-status ${testActive ? 'active' : (testConfigured ? 'configured' : 'unconfigured')}`;
  }
  
  // 生产环境
  const prodConfig = project.environments.production;
  const prodConfigured = prodConfig && prodConfig.trim();
  const prodActive = project.activeEnvironment === 'production';
  
  if (elements.prodEnvStatus) {
    elements.prodEnvStatus.textContent = prodActive ? '已激活' : (prodConfigured ? '已配置' : '未配置');
    elements.prodEnvStatus.className = `environment-status ${prodActive ? 'active' : (prodConfigured ? 'configured' : 'unconfigured')}`;
  }
}

/**
 * 渲染自定义环境
 */
function renderCustomEnvironments() {
  if (!project || !project.customRules) return;
  
  const container = document.getElementById('customEnvironmentsContainer');
  if (!container) return;
  
  const customRules = project.customRules;
  
  if (customRules.length === 0) {
    container.innerHTML = '';
    return;
  }
  
  const html = customRules.map(rule => {
    return `
      <div class="environment-config">
        <hr class="divider">
        <div class="environment-header-simple">
          <h4 class="environment-title-left">
            <i class="fas fa-cog"></i>
            ${escapeHtml(rule.label)}
          </h4>
          <div class="environment-actions">
            <button class="btn btn-sm btn-primary" onclick="saveCustomEnvironment('${rule.id}')" title="保存">
              <i class="fas fa-save"></i> 保存
            </button>
            <button class="btn btn-text btn-sm" onclick="deleteCustomEnvironment('${rule.id}')" title="删除">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
        <div class="form-group">
          <textarea class="textarea-input custom-environment-textarea" data-rule-id="${rule.id}">${escapeHtml(rule.value)}</textarea>
          <small class="form-help">自定义环境配置</small>
        </div>
      </div>
    `;
  }).join('');
  
  container.innerHTML = html;
}

/**
 * 渲染自定义规则
 */
function renderCustomRules() {
  if (!project || !project.customRules || !elements.customRulesContainer) return;
  
  const rules = project.customRules;
  
  if (rules.length === 0) {
    if (elements.emptyCustomRules) {
      elements.emptyCustomRules.style.display = 'block';
      elements.customRulesContainer.innerHTML = '';
      elements.customRulesContainer.appendChild(elements.emptyCustomRules);
    }
    return;
  }
  
  if (elements.emptyCustomRules) {
    elements.emptyCustomRules.style.display = 'none';
  }
  
  const html = rules.map(rule => {
    const isActive = project.activeEnvironment === `custom:${rule.id}`;
    
    return `
      <div class="custom-rule-item ${isActive ? 'active' : ''}" data-rule-id="${rule.id}">
        <div class="rule-header">
          <div class="rule-info">
            <h5 class="rule-name">${escapeHtml(rule.label)}</h5>
            <div class="rule-status ${isActive ? 'active' : 'inactive'}">
              ${isActive ? '已激活' : '未激活'}
            </div>
          </div>
          <div class="rule-actions">
            <button class="btn btn-sm ${isActive ? 'btn-secondary' : 'btn-outline'}" 
                    onclick="toggleCustomRule('${rule.id}')">
              ${isActive ? '<i class="fas fa-stop"></i> 停用' : '<i class="fas fa-play"></i> 激活'}
            </button>
            <button class="btn btn-text btn-sm" onclick="editCustomRule('${rule.id}')" title="编辑">
              <i class="fas fa-edit"></i>
            </button>
            <button class="btn btn-text btn-sm" onclick="deleteCustomRule('${rule.id}')" title="删除">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
        <div class="rule-content">
          <pre class="rule-config">${escapeHtml(rule.value)}</pre>
        </div>
        <div class="rule-meta">
          <small>创建时间: ${formatTime(rule.createdAt)}</small>
          ${rule.updatedAt ? `<small>更新时间: ${formatTime(rule.updatedAt)}</small>` : ''}
        </div>
      </div>
    `;
  }).join('');
  
  if (elements.customRulesContainer) {
    elements.customRulesContainer.innerHTML = html;
  }
}

/**
 * 显示状态
 */
function showLoading() {
  elements.loadingContainer.style.display = 'flex';
  elements.configContainer.style.display = 'none';
}

function showConfig() {
  elements.loadingContainer.style.display = 'none';
  elements.configContainer.style.display = 'block';
}



/**
 * 保存项目名称
 */
async function handleRename() {
  const newName = elements.projectNameEdit.value.trim();
  
  if (!newName) {
    showToast('请输入项目名称', 'warning');
    elements.projectNameEdit.focus();
    return;
  }
  
  if (newName === project.name) {
    showToast('项目名称没有变化', 'info');
    return;
  }
  
  try {
    elements.renameBtn.disabled = true;
    
    const response = await api.renameProject(project.id, newName);
    
    if (response.success) {
      showToast('项目名称保存成功', 'success');
      // 只更新项目数据，不重新加载整个页面
      project.name = newName;
    } else {
      throw new Error(response.error || '保存失败');
    }
  } catch (error) {
    console.error('[Config] 保存项目名称失败:', error);
    showToast('保存失败: ' + error.message, 'error');
  } finally {
    elements.renameBtn.disabled = false;
  }
}

/**
 * 添加自定义规则（新增环境）
 */
async function handleAddCustomRule() {
  const label = elements.customRuleLabel.value.trim();
  const value = elements.customRuleValue.value.trim();
  
  if (!label) {
    showToast('请输入环境名称', 'warning');
    elements.customRuleLabel.focus();
    return;
  }
  
  if (!value) {
    showToast('请输入环境配置', 'warning');
    elements.customRuleValue.focus();
    return;
  }
  
  // 验证配置格式
  const validation = validateDomainConfig(value);
  if (!validation.valid) {
    showToast('配置格式错误: ' + validation.error, 'error');
    elements.customRuleValue.focus();
    return;
  }
  
  try {
    elements.confirmAddCustomRule.disabled = true;
    
    const response = await api.addCustomRule(project.id, label, value);
    
    if (response.success) {
      showToast('新增环境成功', 'success');
      closeModal('addCustomRuleModal');
      
      // 清空表单
      elements.customRuleLabel.value = '';
      elements.customRuleValue.value = '';
      
      // 直接更新本地数据，不重新加载整个页面
      project.customRules.push(response.data);
      renderCustomEnvironments();
    } else {
      throw new Error(response.error || '添加失败');
    }
  } catch (error) {
    console.error('[Config] 新增环境失败:', error);
    showToast('新增失败: ' + error.message, 'error');
  } finally {
    elements.confirmAddCustomRule.disabled = false;
  }
}



/**
 * 删除项目
 */
async function handleDeleteProject() {
      if (elements.deleteConfirmMessage) {
      elements.deleteConfirmMessage.textContent = `确定要删除项目 "${project.name}" 吗？`;
    }
  elements.confirmDeleteAction.onclick = async () => {
    try {
      elements.confirmDeleteAction.disabled = true;
      
      const response = await api.deleteProject(project.id);
      
      if (response.success) {
        showToast(response.message, 'success');
        closeModal('deleteConfirmModal');
        setTimeout(() => goBack(), 1000);
      } else {
        throw new Error(response.error);
      }
    } catch (error) {
      console.error('[Config] 删除项目失败:', error);
      showToast('删除失败: ' + error.message, 'error');
    } finally {
      elements.confirmDeleteAction.disabled = false;
    }
  };
  
  showModal('deleteConfirmModal');
}

/**
 * 重置项目配置
 */
async function handleResetProject() {
  const confirmed = await confirm(
    `确定要重置项目 "${project.name}" 的所有配置吗？\n\n这将清空所有环境配置和自定义规则，且无法撤销。`,
    '重置项目配置'
  );
  
  if (!confirmed) return;
  
  try {
    // 这里应该调用重置API，但当前API中没有单个项目重置
    // 作为替代，我们清空所有配置
    const promises = [
      api.updateEnvironment(project.id, 'test', ''),
      api.updateEnvironment(project.id, 'production', '')
    ];
    
    // 删除所有自定义规则
    if (project.customRules && project.customRules.length > 0) {
      project.customRules.forEach(rule => {
        promises.push(api.deleteCustomRule(project.id, rule.id));
      });
    }
    
    await Promise.all(promises);
    
    showToast('项目配置已重置', 'success');
    await loadProject(project.id);
    
  } catch (error) {
    console.error('[Config] 重置项目失败:', error);
    showToast('重置失败: ' + error.message, 'error');
  }
}

/**
 * 键盘快捷键
 */
function handleKeyboard(e) {
  // Ctrl/Cmd + B: 返回
  if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
    e.preventDefault();
    goBack();
  }
  
  // ESC: 关闭模态框
  if (e.key === 'Escape') {
    const openModal = document.querySelector('.modal.show');
    if (openModal) {
      closeModal(openModal.id);
    }
  }
}

/**
 * 返回主页
 */
function goBack() {
  window.location.href = 'index.html';
}



/**
 * 保存测试环境配置
 */
async function saveTestEnvironment() {
  if (!project) return;
  
  try {
    elements.testEnvSaveBtn.disabled = true;
    const config = elements.testEnvironmentConfig.value.trim();
    
    const response = await api.updateEnvironment(project.id, 'test', config);
    
    if (response.success) {
      showToast('测试环境配置保存成功', 'success');
      // 只更新项目数据，不重新加载整个页面
      project.environments.test = config;
    } else {
      throw new Error(response.error || '保存失败');
    }
  } catch (error) {
    console.error('[Config] 保存测试环境配置失败:', error);
    showToast('保存失败: ' + error.message, 'error');
  } finally {
    elements.testEnvSaveBtn.disabled = false;
  }
}

/**
 * 保存生产环境配置
 */
async function saveProductionEnvironment() {
  if (!project) return;
  
  try {
    elements.prodEnvSaveBtn.disabled = true;
    const config = elements.productionEnvironmentConfig.value.trim();
    
    const response = await api.updateEnvironment(project.id, 'production', config);
    
    if (response.success) {
      showToast('生产环境配置保存成功', 'success');
      // 只更新项目数据，不重新加载整个页面
      project.environments.production = config;
    } else {
      throw new Error(response.error || '保存失败');
    }
  } catch (error) {
    console.error('[Config] 保存生产环境配置失败:', error);
    showToast('保存失败: ' + error.message, 'error');
  } finally {
    elements.prodEnvSaveBtn.disabled = false;
  }
}

/**
 * 新增环境
 */
function handleAddEnvironment() {
  // 直接显示添加自定义规则模态框（现在用作新增环境）
  showModal('addCustomRuleModal');
}

// === 全局函数（供HTML调用） ===

/**
 * 保存自定义环境
 */
window.saveCustomEnvironment = async function(ruleId) {
  const rule = project.customRules.find(r => r.id === ruleId);
  if (!rule) return;
  
  // 获取对应的textarea元素
  const textarea = document.querySelector(`textarea[data-rule-id="${ruleId}"]`);
  if (!textarea) {
    showToast('找不到对应的配置输入框', 'error');
    return;
  }
  
  const newValue = textarea.value.trim();
  if (!newValue) {
    showToast('配置内容不能为空', 'error');
    return;
  }
  
  try {
    // 使用与测试和生产环境相同的API调用方式
    const response = await api.updateEnvironment(project.id, `custom:${ruleId}`, newValue);
    
    if (response.success) {
      showToast('环境配置保存成功', 'success');
      // 更新本地数据
      rule.value = newValue;
    } else {
      throw new Error(response.error || '保存失败');
    }
  } catch (error) {
    console.error('[Config] 保存自定义环境失败:', error);
    showToast('保存失败: ' + error.message, 'error');
  }
};

/**
 * 删除自定义环境
 */
window.deleteCustomEnvironment = async function(ruleId) {
  const rule = project.customRules.find(r => r.id === ruleId);
  if (!rule) return;
  
  const confirmed = await confirm(`确定要删除环境 "${rule.label}" 吗？`);
  if (!confirmed) return;
  
  try {
    const response = await api.deleteCustomRule(project.id, ruleId);
    
    if (response.success) {
      showToast('删除环境成功', 'success');
      // 直接更新本地数据，不重新加载整个页面
      const ruleIndex = project.customRules.findIndex(r => r.id === ruleId);
      if (ruleIndex !== -1) {
        project.customRules.splice(ruleIndex, 1);
        renderCustomEnvironments();
      }
    } else {
      throw new Error(response.error);
    }
  } catch (error) {
    console.error('[Config] 删除自定义环境失败:', error);
    showToast('删除失败: ' + error.message, 'error');
  }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', initConfigPage);